<?php
/*********************************************************************\
*  Copyright (c) 1998-2013, TH. All Rights Reserved.
*  Author :lwj
*  FName  :Chuku.php
*  Time   :2019.10.22
*  Remark :成品出库管理
\*********************************************************************/
FLEA::loadClass('Controller_Sample_Chuku');
class Controller_Sample_SmChuku  extends Controller_Sample_Chuku {

    /**
     * 角色html配置form
     * Time：2018/12/13 15:49:40
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    public function _getMainFormItems() {
        $modelClient = FLEA::getSingleton('Model_Jichu_Client');
        $modelEmploy = FLEA::getSingleton('Model_Jichu_Employ');

        $mainFormItems = array(
            array(
                'type'      =>'comp-text',
                'name'      =>'tiaoMa',
                'title'     =>'产品编号',
                'value'     =>'',
                'width'      =>'100',
            ),
            array(
                'type'       =>'comp-select',
                'name'       =>'clientId',
                'title'      =>'客户',
                'clearable'  =>true,
                'options'    =>$modelClient->getOptions(),
                'filterable' =>true,
                'multiple'   =>false
            ),
            array(
                'type'       =>'comp-select',
                'name'       =>'employId',
                'title'      =>'采样人',
                'clearable'  =>false,
                'options'    =>$modelEmploy->getEmploy(),
                'filterable' =>true,
                'multiple'   =>false
            ),
            array(
                'type'        =>'comp-text',
                'name'        =>'chukuCode',
                'title'       =>'出库单号',
                'readonly'    =>true,
                'clearable'   =>true,
                'value'       =>'',
                'placeholder' =>'系统自动生成，如：'.$this->createNewCode(),
            ),
            array(
                'type'      =>'comp-text',
                'name'      =>'creater',
                'title'     =>'操作人',
                'clearable' =>true,
                'readonly'  =>true,
                'value'     =>$_SESSION['REALNAME'],
            ),
            array(
                'type'      =>'comp-text',
                'name'      =>'reason',
                'title'     =>'原因',
                'clearable' =>true,
                'readonly'  =>false,
                'value'     =>'',
            ),
            array(
                'type'      =>'comp-calendar',
                'name'      =>'chukuDate',
                'title'     =>'出库日期',
                'clearable' =>true,
                'value'     =>date('Y-m-d'),
            ),
            array(
                'type'        =>'comp-textarea',
                'name'        =>'memo',
                'title'       =>'备注',
                'placeholder' =>'',
                'value'       =>'',
            ),
        );
        $sonFormItems[] = array(
                'title'        =>'样品明细',
                'key'          =>"Products",
                'buttonVisble' =>array(
                    'sonUpdown'  =>false,
                    'buttonCopy' =>false,
                    'buttonAdd' =>false,
                ),
                'items' => array(
                    array(
                        'type'      =>'comp-text',
                        'name'      =>'code',
                        'title'     =>'产品编号',
                        'disabled'  =>true,
                        'value'     =>'',
                        'width'      =>'100',
                    ),
                    array(
                        'type'      =>'comp-text',
                        'name'      =>'proName',
                        'title'     =>'产品名称',
                        'disabled'  =>true,
                        'value'     =>'',
                        'width'      =>'100',
                    ),
                    array(
                        'type'      =>'comp-text',
                        'name'      =>'proDesc',
                        'title'     =>'花型颜色',
                        'disabled'  =>true,
                        'value'     =>'',
                        'width'      =>'100',
                    ),
                    array(
                        'type'       =>'comp-text',
                        'name'       =>'type',
                        'title'      =>'样品类型',
                        'value'      =>'',
                        'clearable'  =>false,
                        'disabled'   =>true,
                        'width'      =>'100',
                    ),
                    array(
                        'type'       =>'comp-text',
                        'name'       =>'kuweiName',
                        'title'      =>'库位',
                        'value'      =>'',
                        'clearable'  =>false,
                        'disabled'   =>true,
                        'width'      =>'100',
                    ),
                    array(
                        'type'       =>'comp-text',
                        'name'       =>'kucun',
                        'title'      =>'库存数量',
                        'value'      =>'',
                        'clearable'  =>false,
                        'disabled'   =>true,
                        'width'      =>'100',
                    ),
                    array(
                        'type'      =>'comp-text',
                        'name'      =>'cnt',
                        'title'     =>'出库数量',
                        'clearable' =>true,
                        'value'     =>'',
                        'width'      =>'100',
                    ),
                    array(
                        'type'      =>'comp-text',
                        'name'      =>'price',
                        'title'     =>'单价',
                        'clearable' =>true,
                        'value'     =>'',
                        'width'      =>'100',
                    ),
                    array(
                        'type'      =>'comp-textarea',
                        'name'      =>'memoView',
                        'title'     =>'备注说明',
                        'clearable' =>true,
                        'value'     =>'',
                    ),
                )
            );

        $rules = array(
            'chukuDate'=>array(
                array('required'=>true,'message'=>'出库日期必须'),
            ),
            'employId'=>array(
                array('required'=>true,'message'=>'采样人必须'),
            ),
        );

        return array(
          'success'       =>true,
          'mainFormItems' =>$mainFormItems,
          'sonFormItems'  =>$sonFormItems,
          'rules'         =>$rules,
          'action'        =>$this->_url('Save'),
          'urlRemoveSon'  =>$this->_url('RemoveSonAjax'),
        );
    }

     /**
     * 新增
     * Time：2018/12/17 13:35:37
     * @author li
    */
    function actionAdd() {
        $this->authCheck($this->editFuckId);
        $this->_edit(array());
    }

    function _edit($Arr = array() ,$fromAction) {
        $Arr['fromAction'] = $fromAction;
        if(!$Arr['Products']){
            $Arr['Products'] = array();
        }

        //处理档案
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelKucun = FLEA::getSingleton('Model_Sample_Kucun');
        foreach ($Arr['Products'] as & $v) {
            //查找产品档案的信息
            if($v['productId']){
                $sql = "select x.*,y.kindName from jichu_product x
                    left join jichu_prokind y on x.kindId=y.id
                  where x.id = '{$v['productId']}'";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['productDesc'] = $v['code'].'-'.$tmp[0]['kindName'].'-'.$tmp[0]['proName'];
            }
            if($v['kuweiId']){
                $tmp = $modelKuwei->find($v['kuweiId']);
                $v['kuweiName'] = $tmp['kuweiName'];
            }

            //查找对应的库存数量
            $kucun = $modelKucun->getKucun(array(
                'productId' =>$v['productId'],
                'type'      =>$v['type'],
                'proDesc'   =>$v['proDesc'],
                'kuweiId'   =>$v['kuweiId'],
            ));
            $v['kucun'] = $kucun+$v['cnt'];
        }

        $Arr['flag'] = true;
        // dump($Arr);exit;

        $smarty = & $this->_getView();
        $smarty->assign('title','基本信息');
        $smarty->assign('row',$Arr);
        $smarty->assign('sonTpl','Sample/SmChuku.js');
        $smarty->assign('formItems',$this->_getMainFormItems());
        $smarty->display('Async/MainSonForm.tpl');
    }

    /**
     * @desc ：员工档案查询
     * Time：2017/07/31 15:45:28
     * @author li
    */
    function actionReportViewList() {
        $this->authCheck(0);
        $dateFrom = $_GET['dateFrom'] ? $_GET['dateFrom'] : date('2001-01-01');
        $dateTo = $_GET['dateTo'] ? $_GET['dateTo'] : date('Y-m-d');

        $searchItems = array(
            'dateRange' =>array($dateFrom, $dateTo),
            'barCode'   =>$_GET['code'].'',
        );

        $smarty = & $this->_getView();

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2Table();
        foreach ($fileds as & $fv) {
            $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        }
        $arrFieldInfo = array_merge(
            array(
                "rukuDate"  =>array('text'=>"入库日期",'width'=>'110'),
                "rukuCode"  =>array('text'=>"入库单号",'width'=>'120'),
                "purpose"   =>array('text'=>"用途",'width'=>'100','forKeySearch'=>true),
                "kindName"  =>array('text'=>"产品类别",'width'=>'100'),
                "proCode"   =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'100'),
                "proDesc"   =>array('text'=>"花型颜色",'width'=>'140','forKeySearch'=>true),
                "type"      =>array('text'=>"样品类型",'width'=>'100'),
                "gexing"    =>array('text'=>"格型",'width'=>'90','forKeySearch'=>true),
                "zuzhi"     =>array('text'=>"组织",'width'=>'90','forKeySearch'=>true),
                // "tanli"     =>array('text'=>"弹力",'width'=>'90','forKeySearch'=>true),
                "hzl"       =>array('text'=>"后整理工艺",'width'=>'100'),
                "code"      =>array('text'=>"条码",'width'=>'110','forKeySearch'=>true),
                "cnt"       =>array('text'=>"数量",'width'=>'70'),
                "kuweiName" =>array('text'=>"库位",'width'=>'100'),
            )
            ,$fileds
            ,array(
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
                "creater"   =>array('text'=>"操作人",'width'=>'100'),
                "memoView"  =>array('text'=>"备注",'width'=>''),
            )
        );

        $smarty->assign('title', '入库查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('actionLoadData', $this->_url('GetRows'));
        $smarty->assign('searchItems', $searchItems);
        $smarty->assign('ignoreSearchCache',true);
        $smarty->assign('rowKey','id');
        $smarty->display('Async/TableList.tpl');
    }

    /**
     * 获取计划任务的数据
     * @author li
    */
    public function actionGetRows() {
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }
        FLEA::loadClass('TMIS_Common');

        $post = $this->axiosPost();
        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        $sql="SELECT x.*,y.rukuDate,y.rukuCode,y.reason,y.creater,y.purpose
              from sample_ruku2product x
              left join sample_ruku y on y.id=x.rukuId
              left join jichu_product p on p.id=x.productId
              where 1 ";

        if($arr['rukuCode']!='') {
            $sql.=" and y.rukuCode like '%{$arr['rukuCode']}%'";
        }
        if($arr['proKey']!=''){
            // $sql.=" and(
            //     p.filed1 like '%{$arr['proKey']}%'
            //     or p.filed2 like '%{$arr['proKey']}%'
            //     or p.filed3 like '%{$arr['proKey']}%'
            //     or p.filed4 like '%{$arr['proKey']}%'
            //     or p.filed5 like '%{$arr['proKey']}%'
            //     or p.filed6 like '%{$arr['proKey']}%'
            //     or p.filed7 like '%{$arr['proKey']}%'
            //     or p.filed8 like '%{$arr['proKey']}%'
            //     or p.filed9 like '%{$arr['proKey']}%'
            //     or p.filed10 like '%{$arr['proKey']}%')";
            $sql .= " and p.filed3 like '%{$arr['proKey']}%'";
        }
        if($arr['purpose']!='') {
            $sql.=" and y.purpose like '%{$arr['purpose']}%'";
        }
        if($arr['type']) {
            foreach ($arr['type'] as & $a) {
                $a = "'{$a}'";
            }
            $type = join(',' ,$arr['type']);
            $sql.=" and x.type in ({$type})";
        }
        if($arr['proDesc']!='') {
            $sql.=" and x.proDesc like '%{$arr['proDesc']}%'";
        }
        if($arr['gexing']!='') {
            $sql.=" and x.gexing like '%{$arr['gexing']}%'";
        }
        if($arr['zuzhi']!='') {
            $sql.=" and x.zuzhi like '%{$arr['zuzhi']}%'";
        }
        // if($arr['tanli']!='') {
        //     $sql.=" and x.tanli like '%{$arr['tanli']}%'";
        // }
        if($arr['hzlId']!='') {
            $sql.=" and find_in_set({$arr['hzlId']} ,`hzlId`)";
        }
        if($arr['barCode']!='') {
            $sql.=" and x.code like '%{$arr['barCode']}%'";
        }
        if($arr['reason']!='') {
            $sql.=" and y.reason like '%{$arr['reason']}%'";
        }
        if($arr['proName']!='') {
            $sql.=" and p.proName like '%{$arr['proName']}%'";
        }
        if($arr['proCode']!='') {
            $sql.=" and p.proCode like '%{$arr['proCode']}%'";
        }
        if($arr['guige']!='') {
            $sql.=" and p.guige like '%{$arr['guige']}%'";
        }

        if($arr['productId']) {
            $sql.=" and x.productId = '{$arr['productId']}'";
        }
        if($arr['kuweiId']) {
            $kuweiId = join(',' ,$arr['kuweiId']);
            $sql.=" and x.kuweiId in ({$kuweiId})";
        }
        if($arr['dateRange']){
            list($datefrom ,$dateTo) = $arr['dateRange'];
            $sql .= " and y.rukuDate >= '{$datefrom}' and y.rukuDate <= '{$dateTo}'";
        }
        $sql .=" order by y.id desc,x.id asc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        // dump($rowset);exit;
        foreach ($rowset as $key => & $v) {
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);

            $v['cnt'] = round($v['cnt'],6);

            $_tmp = $modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_tmp['kuweiName'];

            //图片预览
            if($v['imageId']){
                $sql = "SELECT * from jichu_image where id in({$v['imageId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                // $tmp = array_col_values($tmp,'path');
                foreach ($tmp as & $ii) {
                    $v['imageSrc'][] = array(
                        'path'=>TMIS_Common::_imageSrc($ii['smallPath'])
                    );
                }
            }

            // 查找后整理工艺
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }
        }

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>array(),
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;
    }

    /**
     * Time:2019年12月24日 09:19:24
     * 获取计划对应的半成品入库信息
     * @author lxd
    */
    public function actionGetProduct()
    {
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }
        FLEA::loadClass('TMIS_Common');
        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2TableNew();

        $post = $this->axiosPost();
        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        $sql="SELECT x.*,y.rukuDate,y.rukuCode from sample_ruku2product x
              left join sample_ruku y on y.id=x.rukuId
              left join jichu_product p on p.id=x.productId
              where 1 ";

        if($_GET['code']){
            $sql.=" and x.code = '{$_GET['code']}'";
        }
        if($arr['kuweiName']){
            $str = "SELECT id from jichu_kuwei where kuweiName like '%{$arr['kuweiName']}%'";
            $tmp = $this->_modelExample->findBySql($str);
            if($tmp){
                $kuweiIds = join(',',array_col_values($tmp,'id'));
                !$kuweiIds && $kuweiIds = '-1';
            }else{
                $kuweiIds = "-1";
            }
            $sql .= " and x.kuweiId in ({$kuweiIds})";
        }
        $sql .=" order by y.id desc,x.id asc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        // dump($rowset);exit;
        foreach ($rowset as $key => & $v) {
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);

            //出库数量
            $sql = "SELECT sum(cnt) as cnt from sample_chuku2product where code = '{$v['code']}' and productId = '{$v['productId']}' and proDesc = '{$v['proDesc']}' and hzlId = '{$v['hzlId']}' and kuweiId = '{$v['kuweiId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['kucun'] = round(($v['cnt']-$tmp[0]['cnt']),6);

            $_tmp = $modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_tmp['kuweiName'];

            //图片预览
            if($v['imageId']){
                $sql = "SELECT * from jichu_image where id in({$v['imageId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                // $tmp = array_col_values($tmp,'path');
                foreach ($tmp as & $ii) {
                    $v['imageSrc'][] = array(
                        'path'=>TMIS_Common::_imageSrc($ii['smallPath'])
                    );
                }
            }

            // 查找后整理工艺
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }
            $v['rowKey'] = $v['id'];
            unset($v['cnt']);continue;
        }

        $arrFieldInfo = array_merge(
            array(
                "rukuDate"  =>array('text'=>"入库日期",'width'=>'110'),
                "rukuCode"  =>array('text'=>"入库单号",'width'=>'120'),
                "purpose"   =>array('text'=>"用途",'width'=>'100','forKeySearch'=>true),
                "kindName"  =>array('text'=>"产品类别",'width'=>'100'),
                "proCode"   =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'100'),
                "proDesc"   =>array('text'=>"花型颜色",'width'=>'140','forKeySearch'=>true),
                "type"      =>array('text'=>"样品类型",'width'=>'100'),
                "gexing"    =>array('text'=>"格型",'width'=>'90','forKeySearch'=>true),
                "zuzhi"     =>array('text'=>"组织",'width'=>'90','forKeySearch'=>true),
                // "tanli"     =>array('text'=>"弹力",'width'=>'90','forKeySearch'=>true),
                "hzl"       =>array('text'=>"后整理工艺",'width'=>'100'),
                "code"      =>array('text'=>"条码",'width'=>'110','forKeySearch'=>true),
                "cnt"       =>array('text'=>"数量",'width'=>'70'),
                "kuweiName" =>array('text'=>"库位",'width'=>'100'),
            )
            ,$fileds
            ,array(
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
                "creater"   =>array('text'=>"操作人",'width'=>'100'),
                "memoView"  =>array('text'=>"备注",'width'=>''),
            )
        );
        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>$arrFieldInfo,
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;
    }

    /**
     * 根据条码获取库存
     * Time：2021年1月11日 14:02:21
     * @author lxd
    */
    function actionGetKucun(){
        $post = $this->axiosPost();
        $modelProduct = FLEA::getSingleton("Model_Jichu_Product");
        $modelKuwei = FLEA::getSingleton("Model_Jichu_Kuwei");
        if($post['code']){
            $sql = "SELECT * FROM sample_ruku2product where code = '{$post['code']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            foreach ($tmp as $k => & $v) {
                $pro = $modelProduct->find($v['productId']);
                $v['proName'] = $pro['proName'];
                $kuwei = $modelKuwei->find($v['kuweiId']);
                $v['kuweiName'] = $kuwei['kuweiName'];

                //查找出库情况
                $sql = "SELECT sum(cnt) as kucun from sample_chuku2product where code = '{$v['code']}' and kuweiId = '{$v['kuweiId']}' and proDesc = '{$v['proDesc']}' and hzlId = '{$v['hzlId']}' and productId = '{$v['productId']}'";
                $temp = $this->_modelExample->findBySql($sql);
                if($temp[0]['kucun']){
                    $v['kucun'] = round(($v['cnt'] - $temp[0]['cnt']),6);
                }else{
                    $v['kucun'] = round($v['cnt'],6);
                }
                unset($v['cnt']);continue;
            }
            $row = $tmp;
            if($row){
                echo json_encode(array('success'=>true,'data'=>$row));
            }else{
                echo json_encode(array('success'=>false,'msg'=>'该条码没有入库记录,请确认'));
            }
            exit;
        }
    }
}

?>